package com.macro.mall.tiny.security.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;

/**
 * @author Tyrone
 * @date 2024/10/14 15:36
 */
public class CharUtil {
    static HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
    {
        format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        format.setVCharType(HanyuPinyinVCharType.WITH_V);
    }

    public static String getFirstLetter(String input) {
        if (input == null || input.isEmpty()) {
            return "";
        }
        char firstChar = input.charAt(0);
        try {
            if (Character.toString(firstChar).matches("[\\u4E00-\\u9FA5]+")) {
                String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(firstChar, format);
                if (pinyinArray != null) {
                    return pinyinArray[0].substring(0, 1);
                }
            } else {
                return Character.toString(firstChar).toUpperCase();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }
}
